<template>
	<view class="p-bot120" v-if='art'>
		<status-bar title='文章详情' :goHome='fromShare'></status-bar>
		<backTop v-if='toTop'></backTop>

		<view class="particularsContent padding30">
			<view class="size46 color_22 bold500 p-bot60">{{art.website_article_title}}</view>
			<view class="size26 d-flex j-sb">
				<view class="d-flex a-center">
					<view class="color_44 bold500" style="max-width: 120rpx;" v-if="art.articleSource">{{art.articleSource}}</view>
					<view class="divider" v-if="art.articleSource"></view>
					<view class="color_99 bold400">{{art.website_article_addtime}}</view>
					<view class="divider"></view>
					<view class="color_99 bold400">阅读{{art.website_article_views}}</view>
				</view>
				<view class="d-flex a-center">
					<view class="m-right8" v-if='art.poster' @click="getPoster">
						<u-button icon="share-square" text="分享" size="mini" shape="circle" plain></u-button>
					</view>
					<view @click="artCollect">
						<u-button v-if="art.collect" text="已收藏" size="mini" shape="circle" plain></u-button>
						<u-button v-else :color="color" icon="star" text="收藏" size="mini" shape="circle" plain></u-button>
					</view>
				</view>
			</view>
			<!-- 视频 -->
			<view class="videoBox m-top40" :class="{'videoFixed':toTop}" v-if="art.video_url">
				<video class="wh bor_radius_10" :src="art.video_url" controls @play="videoPlay" id="myVideo"></video>
			</view>
			<view class="videoBox m-top40" v-if="art.video_url&&toTop"></view>
			<!-- 音频 -->
			<view class="audioBox m-top40 d-flex j-sb a-center p-right50" :class="{'audioFixed':toTop}" v-if="art.website_article_url">
				<image :src="imgUrl + 'Uploads/diy/img/audioPlay.png'" class="disk playSpin" :style="{'animation-play-state':onPlay?'running' :'paused'}"></image>
				<view class="p-re">
					<u-slider :value="currentTime" :max="duration" @change="sliderChange" activeColor="#8396A6" inactiveColor="#F9FCFF" blockSize="12"></u-slider>
					<view class="time p-ab d-flex j-sb h7" style="color:#708393;">
						<text>{{ formatTime(currentTime) }}</text>
						<text>{{ formatTime(duration) }}</text>
					</view>
				</view>
				<u-icon name="play-circle" color="#fff" size="28" @click="playAudio" v-if="!onPlay"></u-icon>
				<u-icon name="pause-circle" color="#fff" size="28" @click="playAudio" v-if="onPlay"></u-icon>
			</view>
			<view class="m-top40" style="height: 84rpx" v-if="art.website_article_url&&toTop"></view>
			<!-- 富文本 -->
			<view class="u-content m-top40">
				<u-parse :content="art.website_article_content" :domain="imgUrl" :scrollTable="true" :selectable="true" :useAnchor="true"></u-parse>
			</view>
			<view class="u-content m-top40" v-if="art.jumpRoute.state == 1" @click="toUrl(art.jumpRoute.route)">
				<image :src="imgUrl+art.jumpRoute.img" mode="widthFix" class="wh"></image>
			</view>
			
			<view class="m-top30 d-flex j-sb p-left40 p-right40" v-if="bid != 'jQkF7oW0EhZ6WEmPYCw04A=='">
				<u-button :color="color" :icon="art.zan?'thumb-up-fill':'thumb-up'" :text="'点赞('+art.website_article_zan+')'" shape="circle" plain
					:customStyle="{width:'242rpx',height:'66rpx'}" @click="artZan"></u-button>
				<u-button :color="color" iconColor="#ffffff" icon="chat" :text="'评论('+art.website_article_comment+')'" shape="circle" @click="handleReply"
					:customStyle="{width:'242rpx',height:'66rpx'}"></u-button>
			</view>

			<!-- 附件 -->
			<view class="underline m-top40" :style="{color:color}" v-if='art.attachment_name' @click="openFile(art.attachment_url)">
				下载{{ art.attachment_name }}
			</view>
		</view>

		<!-- 表单 -->
		<formList v-if='form_list' :ids='form_list' info='false'></formList>
		
		<!-- 评论 -->
		<view class="p-top30 p-left30 p-right30" v-if="art && commentList.length">
			<u-divider text="评论" textPosition="left" textSize="19" textColor="#222"></u-divider>
			<view class="m-top60">
				<view v-for="(item,index) in commentList" :key="index">
					<view class="d-flex" @click="handleReply(item)">
						<u-avatar :src="$imgUrls(item.userInfo.v_headimg)" shape="circle" size="35"></u-avatar>
						<view class="p-left12 flex-1">
							<view class="d-flex j-sb a-center m-bot20">
								<text class="size26 color_22">{{ item.userInfo.v_name || '用户' }}</text>
								<text class="iconfont icon-pinglun color_66 size36"></text>
							</view>
							<view class="color_77 size28 line34 m-bot20">{{ item.content_text }}</view>
							<view class="color_99 h6">{{ item.replyData }}</view>
							<view class="m-top20 bgF5 padding10" v-if="item.reply">
								<view v-for="(itm,idx) in item.reply" :key="idx" class="line40">
									<text class="color_22 size26 m-right10">{{ itm.userInfo.v_name || '用户' }}: </text>
									<text class="color_77 size26">{{ itm.content_text }}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="line" v-if="index != commentList.length - 1"></view>
				</view>
			</view>
			<!-- <emptys empty="comment" title="暂无评论" :top="0" v-else></emptys> -->
		</view>
		
		<!-- <contact v-if="art"></contact> -->

		<view class="footer padding20-30" v-if="onReply">
			<u--input v-model="comment" type ="textarea" confirmType="send" :placeholder="placeholder" focus @confirm="makeComment()" @blur="onReply = false"
				:customStyle="{background: '#fff'}"></u--input>
		</view>

		<empty v-if="error" cat='4' :msg='errMsg'></empty>
	
		<showModel @cancelFunc='showModal=false' goHome='0' v-if='showModal' type='2'></showModel>

		<!-- 分享海报 -->
		<view class="mask flex-box align-center flex-center" :style="{'padding-top': navHeight+System.statusBarHeight+'px'}" v-if='showPoster' @click="showPoster=false">
			 <view>
				<image :src="posterImg" mode="widthFix" class="viewbox55" :show-menu-by-longpress='true' @click.stop></image>
				<view class="save-poster thmeBg" :style="{'--color':color}" @click.stop="saveEwm">
					<text>下载海报</text>
				</view>
			 </view>
		</view>

		<view class="float-nav">
			<view class="item bgwhite bor_radius flexac" v-if="art.contact_phone" @click.stop="$common.Tel(art.contact_phone)">
				<text class="iconfont icon-dianhua size42"></text>
			</view>
			<view class="item bgwhite bor_radius flexac m-top20" v-if="art.wechat" @click.stop="showWechat = true">
				<text class="iconfont icon-weixin color_wechat size50"></text>
			</view>
		</view>

		<view class="mask flexac f-column" @click="showWechat = false" v-if="showWechat">
            <image class="viewbox5" :src="$imgUrls(art.wechat)" mode="aspectFit" show-menu-by-longpress style="height: 890rpx;" @click.stop></image>
            <text class="iconfont icon-guanbi size60" @click="showWechat = false"></text>
        </view>
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	import formList from '@/components/formList.vue'
	var that
	export default {
		components: {
			formList
		},
		data() {
			return {
				imgUrl: this.imgUrl,
				fromShare: 0, // 1显示'返回首页'按钮
				toTop: false,
				artId: '',
				art: '', // 详情
				error: false,
				errMsg: '',
				showModal: false,
				showPoster: false,
				posterImg: '',
				form_list: '',
				videoContext: null,
				// 音频
				audioContext: null,
				onPlay: false,
				currentTime: 0,
				duration: 0,
				// 评论
				commentList: [],
				comment: '',
				onReply: false,
				commentId: '',
				placeholder: '友善评论哦',
				showWechat: false
			}
		},
		onLoad(options) {
			that = this
			if (options.fromShare) {
				that.fromShare = options.fromShare
			}
			that.artId = options.artId
			// 获取文章详情
			that.getDetail()

			// 获取评论
			that.getComment()
		},
		onUnload(){
			if(that.audioContext){
				that.audioContext.destroy()
				that.audioContext.offTimeUpdate()
				that.audioContext.offEnded()
			}
		},
		methods: {
			getDetail(){
				that.$http.get({
					url: '/zzjApp/articleInfo',
					data: {
						website_article_id: that.artId
					}
				}).then(res => {
					if (res.data) {
						if(res.data.jump_url) return that.$rectTo('/userPage/onlineService/webHttp?isURL=' + res.data.jump_url)
						that.art = res.data
						if(res.data.order_id && res.data.order_id != 0){
							that.form_list = [{'order_id': res.data.order_id}]
						}
						if(that.art.video_url){
							that.videoContext = uni.createVideoContext('myVideo')
						}
						if(!that.art.website_article_url) return
						that.initAudio()
					} else {
						that.error = true
						that.errMsg = res.msg
					}
				})
			},
			getPoster(){
				if (!that.vid) return that.showModal = true
				uni.showLoading({
					title: '海报生成中...',
					mask: true
				})
				that.$http.post({
					url: '/singleSaleApi/getArticleCode',
					data: {
						website_article_id: that.artId,
						path: '/#/pages/index/index?artId=' + that.artId + '&pageType=4',
					}
				}).then(res=>{
					if(res.data && res.data.imgUrl){
						uni.downloadFile({
							url: res.data.imgUrl,
							success(res1){
								uni.hideLoading()
								that.showPoster = true
								that.posterImg = res1.tempFilePath
							}
						})
					} else {
						uni.hideLoading()
						that.$Toast('获取海报出错！')
					}
				})
			},
			saveEwm(){
				uni.getSetting({
					success(res){ // 获取用户授权结果
						if(!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success(){
									that.saveImgToLocal()
								},
								fail() {
									that.$Toast('拒绝后将无法保存图片！') 
								}
							})
						} else{ // 已授权保存到相册
							that.saveImgToLocal()
						}
					}
				})
			},
			saveImgToLocal(){
				uni.saveImageToPhotosAlbum({
					filePath: that.posterImg,
					success(){
						that.$Toast('保存成功')
					},
					fail(){
						that.$Toast('保存失败')
					}
				})
			},
			openFile(url){
				if(url){
					uni.showLoading({
						title: '请稍等'
					})
					uni.downloadFile({
						url: that.baseUrl + url,
						success(res){
							var filePath = res.tempFilePath
							uni.openDocument({
								filePath,
								success(res){
									console.log('打开文档成功')
								},
								complete(){
									uni.hideLoading()
								}
							})
						},
						fail(err){
							console.log(err)
							uni.hideLoading()
						}
					})
				} else{
					that.$Toast('获取路径失败！')
				}
			
			},
			artCollect() {
				if (!that.vid) return that.showModal = true
				that.$http.post({
					url: '/singleSaleApi/article_collect',
					data: {
						website_article_id: that.artId
					}
				}).then(res => {
					if(res.code != 200) return that.$Toast(res.msg)
					that.art.collect = that.art.collect ? 0 : 1
				})
			},
			initAudio(){
				that.audioContext = uni.createInnerAudioContext()
				that.audioContext.src = that.art.website_article_url
				that.audioContext.onTimeUpdate(()=>{
					that.currentTime = that.audioContext.currentTime
					that.duration = that.audioContext.duration
					// that.percent = Math.round(that.currentTime/that.duration*100)
				})
				that.audioContext.onEnded(()=>{
					that.onPlay = false
					that.currentTime = 0
				})
			},
			videoPlay(){
				if(that.onPlay){ // 暂停音频
					that.onPlay = false
					that.audioContext.pause()
				}
			},
			playAudio(){
				that.onPlay = !that.onPlay
				if(that.onPlay){ // 暂停或停止
					that.audioContext.play()
					if(that.videoContext){ // 暂停视频
						that.videoContext.pause()
					}
				} else{ // 正在播放
					that.audioContext.pause()
				}
			},
			formatTime(val){
				let m = parseInt(val / 60)
				let s = parseInt(val % 60)
				m = m < 10 ? '0' + m : m
				s = s < 10 ? '0' + s : s
				return m + ':' + s
			},
			sliderChange(val){
				// that.audioContext.seek(that.duration*(val/100))d)
				// 跳转会导致onTimeUpdate不更新
				if(that.onPlay){
					that.audioContext.pause()
					that.audioContext.seek(val)
					setTimeout(()=>{
						that.audioContext.play()
					},100)
					return 
				}
				that.audioContext.seek(val)
				that.currentTime = val
			},
			artZan(){
				if (!that.vid) return that.showModal = true
				that.$http.post({
					url: '/zzj_singleSaleApi/zanArticle',
					data: {
						article_id: that.artId,
						operation: that.art.zan ? 2 : 1 // 点赞传1，取消传2，zan为0是未点赞
					}
				}).then(res=>{
					if(res.code != 100) return that.$Toast(res.msg)
					that.art.zan = that.art.zan ? 0 : 1
					let num = parseInt(that.art.website_article_zan)
					that.art.website_article_zan = that.art.zan ? num + 1 : num - 1
				})
			},
			getComment(){
				that.$http.get({
					url: '/zzj_singleSaleApi/getArticleCommentList',
					data: {
						article_id: that.artId
					}
				}).then(res=>{
					that.commentList = res.data || []
				})
			},
			handleReply(item){
				if (!that.vid) return that.showModal = true
				if(!that.onReply){
					that.onReply = true
				}
				that.commentId = item ? item.common_id : ''
				that.placeholder = item ? `回复${item.userInfo.v_name || '用户'}:` : '友善评论哦'
			},
			makeComment(){
				that.$http.post({ 
					url: '/zzj_singleSaleApi/articleComment',
					data: {
						article_id: that.artId,
						content_text: that.comment,
						common_id: that.commentId
					}
				}).then(res=>{
					if(res.code != 100) return that.$Toast(res.msg)
					that.comment = ''
					that.getComment()
					that.art.website_article_comment = parseInt(that.art.website_article_comment) + 1
				})
			}
		},
		computed:{
			...mapState(['color','vid','share','System','navHeight','bid'])
		},
		onShareAppMessage(){ // 设置分享信息
			that.$addShareNum('articles', that.artId, '1')
			const share = that.share
			return {
				title: that.art.website_article_title ? that.art.website_article_title : share.title,
				desc: that.art.website_article_info ? that.art.website_article_info : share.desc,
				path: '/pages/index/index?share_v_id=' + that.vid + '&pageType=4&artId=' + that.artId, // 点击链接进入的页面
				imageUrl: that.art.website_article_img ? that.$imgUrls(that.art.website_article_img) : share.imageUrl
			}
		},
		onPageScroll(e){
			if (e.scrollTop > 360) {
				that.toTop = true
			} else {
				that.toTop = false
			}
		},
		onShareTimeline(){
			that.$addShareNum('articles', that.artId, '2')
			const share = that.share
			return {
				title: that.art.website_article_title ? that.art.website_article_title : share.title,
				query: `share_v_id=${that.vid}&artId=${that.artId}&fromShare=1`,
				imageUrl: that.art.website_article_img ? that.$imgUrls(that.art.website_article_img) : share.imageUrl
			}
		}
	}
</script>

<style scoped lang="scss">
	.divider {
		width: 2rpx;
		height: 30rpx;
		background: #BEC5CE;
		margin: 0 14rpx;
	}
	.videoBox {
		width: 100%; 
		height: 388rpx;
	}
	.videoFixed {
		position: fixed;
		right: 0;
		top: 50%;
		margin-top: -97rpx;
		z-index: 10;
		width: 345rpx;
		height: 194rpx;
	}
	.audioBox {
		width: 100%;
		height: 84rpx;	
		background: #B8C3CD;
		border-radius: 42rpx;
		.disk {
			width: 98rpx;
			height: 98rpx;
		}
		.time {
			width: 100%;
			bottom: 0;
			left: 0;
		}
	}
	.playSpin {
		animation: spin 5s linear infinite;
	}
	@keyframes spin {
		from {transform: rotate(0deg)}
		to {transform: rotate(360deg)}
	}
	::v-deep slider {
		width: 440rpx;
		margin: 20rpx 0;
	}
	.audioFixed {
		position: fixed;
		bottom: 10rpx;
		left: 50%;
		margin-left: -345rpx;
		z-index: 10;
		width: 690rpx;
	}
	::v-deep .u-divider__text {
		font-weight: bold;
	}
	.line {
		width: 100%;
		height: 1rpx;
		background: #CFCFCF;
		margin: 20rpx 0;
	}
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 20;
		width: 100%;
		background: #f6f6f6;
	}
	.save-poster{
		color: white;
		width: 222rpx;
		text-align: center;
		line-height: 66rpx;
		border-radius: 10rpx;
		margin: 20rpx auto 0;
	}
	.float-nav {
		position: fixed;
		right: 24rpx;
		bottom: calc(250rpx + constant(safe-area-inset-bottom));
        bottom: calc(250rpx + env(safe-area-inset-bottom));
		z-index: 30;
		.item {
			width: 80rpx;
			height: 80rpx;
			box-shadow: 0 4rpx 16rpx 0 rgba(0,0,0,.16);
		}
	}
</style>
